package com.kfm.base.structure;

import java.util.Random;
import java.util.Scanner;

public class Exer01 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入密码位数：");
        int num = input.nextInt();

        String pass = password(num);

        System.out.println(pass);

    }


    public static String password(int n){
        if (n <= 0) return "";
        Random rand = new Random();
        int letter = rand.nextInt(26) + 65;
        StringBuilder sb = new StringBuilder();
        sb.append((char)letter);

        boolean hasNum = false;
        for (int i = 1; i < n; ) {
            int type = rand.nextInt(3);
            char c = (char)switch (type){
                case 0 -> {
                    hasNum = true;
                    yield rand.nextInt(10) + 48;
                }
                case 1 -> rand.nextInt(26) + 65;
                default -> rand.nextInt(26) + 97;
            };
            if (sb.indexOf(String.valueOf(c)) == -1) {
                sb.append(c);
                i ++;
            }
        }

        if (!hasNum){ // 没数字
            int index = rand.nextInt(n - 1) + 1;
            int c = rand.nextInt(10);
            sb.replace(index, index + 1, String.valueOf(c));
        }

        return sb.toString();
    }
}
